<!-- 创建、修改任务,单次读取,循环读取,循环带外采集,单次带外采集,执行命令-->
<template>
    <Modal
        v-model="modal.show"
        :title="modal.title"
        :loading="modal.loading"
        :mask-closable="false"
        @on-ok="saveTask"
        @on-cancel="closeModal"
        :width="modal.width">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="60">
        <FormItem label="类型" prop="taskType">
            <Select filterable v-model="formValidate.taskType" placeholder="请选择类型" @on-change="changeTaskType">
                <Option  v-for="item in taskList" :key="item.value" :value="item.value">{{item.label}}</Option>
            </Select>
        </FormItem>
        <FormItem label="名称" prop="name">
            <Input v-model.trim="formValidate.name" placeholder="请输入中文、数字、字母、英文括号、下划线或者中划线，名称长度为1-50个字符"
                :maxlength="50"></Input>
        </FormItem>
        <FormItem label="配置" prop="configer" style="position:relative">
            <!-- <Icon type="md-add-circle" :size="20" style="cursor:pointer;position:absolute;top:-20px;right:0px" @click="taskConfigerMess = true" title="配置管理"/> -->
            <Select filterable v-model="formValidate.configer" placeholder="请选择配置"   filterable clearable  @on-change="showConfiguration" >
                <Option  v-for="item in configList" :key="item.id" :value="item.id"  @mouseenter.native="mouseOverConfiger($event,item.id)" @mouseleave.native="mouseLeaveConfiger($event,item.id)" @click.native="ddd">{{item.name}}</Option>
            </Select>
            <div v-show="configurationInformation" :style="{position:'absolute',left:cardPanelLeft,top:cardPanelTop,zIndex:'9999999999999999',}" @mouseenter="jinru" @mouseleave="yichu" @click="ddd">
                <Card :style="{minWidth:'350px',maxWidth:'600px'}"  >
                    <p slot="title" style="position:relative">
                        <Icon type="ios-construct"></Icon>
                        {{configPanel.configName}}
                        <span slot="title" style="position:absolute;right:0px">
                            <Icon type="ios-contact"></Icon>
                            {{configPanel.configCreatorName}}
                        </span>
                    </p>
                    <ul>
                        <li><span class="_dot"></span>Path：{{configPanel.configPath}}</li>
                        <li><span class="_dot"></span>Systype：{{configPanel.configSystype}}</li>
                        <li><span class="_dot"></span>Content：<pre style="word-break: break-all;white-space: pre-wrap;">{{configPanel.configContent}}</pre></li>
                        <li><span class="_dot"></span>CreateTime:{{configPanel.configCreateTime}}</li>
                        <li><span class="_dot"></span>Desc:{{configPanel.configDescription}}</li>
                        <template v-if="formValidate.taskType === 'qga_write'">
                            <li><span class="_dot"></span>Path：{{configPanel.configPath}}</li>
                            <li><span class="_dot"></span>Systype：{{configPanel.configSystype}}</li>
                            <li><span class="_dot"></span>KAFKA地址：{{configPanel.kafkaAdress}}</li>
                            <li><span class="_dot"></span>TOPIC：{{configPanel.configTopic}}</li>
                            <!-- <li><span class="_dot"></span>读取周期：{{configPanel.configPeriod}}秒</li> -->
                            <li><span class="_dot"></span>Desc:{{configPanel.configDescription}}</li>
                        </template>
                    </ul>
                </Card>
            </div>
        </FormItem>
        <FormItem v-model="formValidate.selectedVmData"  label="虚拟机">
            <span class="starlet">*</span>
            <input type="hidden" >
            <Tag v-for="item in formValidate.selectedVmData" :key="item.name" :name="item.id" closable @on-close="handleClose2" color="primary" type='dot' >{{ item.name }}</Tag>
        </FormItem>
        <div style="text-align:right">
            <Button type="primary" @click="addSelectedData" style="margin-right:17px">添加</Button>
            <Input placeholder="请输入名称" style="width: 210px" v-model="queryVm.name" clearable></Input>
            <Input placeholder="请输入IP" style="width: 210px" v-model="queryVm.ipAddress" clearable></Input>
            <Button type="primary" @click="refreshVmList()" style="margin-left:5px">搜索</Button>
        </div>
        <Table border ref="vmTable" :columns="vmColumns" :data="vmList"  :stripe="true" :show-header="true" size="small" style="margin-top:10px" @on-selection-change="getSelectedData"></Table>
        <Page :total="vmTotal"  show-elevator :current="queryVm.pageIndex" :page-size="queryVm.pageSize" :show-total= true  @on-change="changeVmPage" @on-page-size-change="changeVmSize" class-name="flex-center"/>
        <FormItem label="属性" >
            <cusAttribute ref="cusAttribute" @func="getMsgFormSon" v-bind:msgVal="propertiesData"></cusAttribute>
        </FormItem>
        <FormItem label="描述" prop="description">
            <Input v-model.trim="formValidate.description" type="textarea" :maxlength="200"
                :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入描述"></Input>
        </FormItem>
    </Form>
</Modal>
</template>
<script>
    import { validateName } from '@/libs/reg'
    import {addTask,updateTask} from '@/api/process/task'
    import {loadItemConfiguration,showConfiguration,getAllVm,hostDetail} from '@/api/drill.js'
    import cusAttribute from '../../cusAttribute'
    export default {
        name:'EditModal',
        components:{cusAttribute},
        props:{
            testId:{
               type:String,
               required: true
            },
            projectId:{
                type:String,
                required: true
            }
            // taskType:{
            //     type:String,
            //     required: true
            // }
        },
        data(){
            const validateFile = (rule,value,callback) => {
                if(!value){
                    callback('请选择文件');
                }else if(value.split('.').pop() !== 'json'){
                    callback('请选择文件');
                }
                callback()
            }
            return {
                modal:{
                    show:this.value,
                    title:'创建任务',
                    loading:true,
                    width:600
                },
                formValidate: {
                    name: '',
                    configer: '',
                    osType:'',
                    path:'',
                    category:'',
                    type:'',
                    content:'',
                    selectedVmData:[],
                    description: '',
                    vmName:'',
                    vmIP:'',
                    taskMode:'normal',
                    taskType:''
                },
                ruleValidate: {
                    name: [
                        {
                            required: true,
                            max: 64,
                            message: '模板名称长度为1-64个字符',
                            trigger: 'blur'
                        },
                        {
                            validator: validateName,
                            trigger: 'blur'
                        }
                    ],
                    taskType: [
                        { required: true, message: '请选择类型', trigger: 'change'},
                    ],
                    configer: [
                        { required: true, message: '请选择配置', trigger: 'change'},
                    ],
                    taskMode: [
                        { required: true, message: '', trigger: 'blur'}
                    ],
                    selectedVmData:[
                        {required:true ,message:"请选择虚拟机"}
                    ],
                    description: [{ max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }]
                },
                propertiesData:[],
                configList:[],
                configPanel:{},
                configerSystype:'',
                configurationInformation:false,
                cardPanelLeft:'3px',
                cardPanelTop:'3px',
                configPanel:{
                    configPath:'',
                    configSystype:'',
                    configContent:'',
                    configDescription:'',
                    configCreateTime:'',
                    configCreatorName:'',
                    configName:'',
                },
                hoverCdraBol:false,
                vmColumns:[
                    {
                        type:'selection',
                        width:60,
                        align:'center'
                    },

                    {
                        title:this.$t('name'),
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'IP',
                        key:'IP',
                        align:'center',
                        render:(h,params)=>{
                            let value = params.row.IP;
                            let oIP_ = [];
                            value.forEach((item,i)=>{
                                oIP_.push(h("p",{
                                    color:'#000',
                                },item))
                            })
                            return h("div",oIP_)
                        }
                    },
                    {
                        title:this.$t('Systype'),
                        key:'sysType',
                        align:'center',
                    },
                    {
                        title:this.$t('Add'),
                        key:'add',
                        align:'center',
                        width:80,
                        render:(h,params) =>{
                            let _this = params;
                            return h('Button', {
                                props: {
                                    type: 'primary',
                                },
                                on:{
                                    click: (e) => {
                                        if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                            this.$Message.info("已添加")
                                            return;
                                        }
                                        // alert('-')
                                        this.addVmAfterTable(_this.row)
                                        this.selectedVmDataTable.push(_this.row.id)
                                        this.formValidate.selectedVmData.push({
                                            "name":_this.row.name,
                                            "id":_this.row.id
                                        })
                                    },
                                }
                            }, "+");
                        }
                    }
                ],
                queryVm:{
                    pageIndex:1,
                    pageSize:10,
                    order:"asc",
                    sortBy:"name",
                    name:'',
                    ipAddress:'',
                    sysType:'',
                    projectId:this.prjid
                },
                vmList:[],
                vmTotal:0,
                selectedVmDataTable:[],
                selectedDataConfiger:[],
                taskList:[
                    {
                        value:'qga_read',
                        label:'单次读取'
                    },
                    {
                        value:'qga_loop_read',
                        label:'循环读取'
                    },
                    {
                        value:'once_capture',
                        label:'单次带外采集'
                    },
                    {
                        value:'loop_capture',
                        label:'循环带外采集'
                    },
                    {
                        value:'qga_write',
                        label:'文件写入'
                    },
                    {
                        value:'qga_execute_cmd',
                        label:'执行命令'
                    },
                    {
                        value:'EYDD',
                        label:"操作任务"
                    }
                ]
            }
        },
        computed:{
            
        },
        watch: {
            
        },
        mounted(){
            this._formValidate = {...this.formValidate};
            this._queryVm = {...this.queryVm};
        },
        methods:{
            saveTask(){
                this.$refs.formValidate.validate((valid) => {
                    if(valid){
                        let params = {
                            name:this.formValidate.name,
                            configName:this.configPanel.configName,
                            configId:this.formValidate.configer,
                            description :this.formValidate.description,
                            deviceIdList :this.selectedVmDataTable,
                            deviceType:"VM",
                            taskType:this.formValidate.taskType,
                            testId:this.testId,
                            metadata:this.metadataConfigerInfor,
                            properties:this.properties,
                            taskMode:this.formValidate.taskMode,
                        };
                        if(this.type === 'update'){
                            //修改模板
                            updateTask(this.formValidate.id,params).then(({code,data,message}) => {
                                if(code == 1){
                                    this.$Message.info('修改任务成功');
                                    this.closeModal();
                                    this.$emit('ok','update')
                                }else{
                                    this.$Message.error(message);
                                }
                            }).catch(e => {
                                this.$Message.error('修改失败');
                            }).finally(() => {
                                this.cancelLoading();
                            })
                        }else{
                            // 竞赛页面生成模板
                            addTask(params).then(({code,data,message}) => {
                                if(code == 1){
                                    this.$Message.info('创建任务成功');
                                    this.closeModal();
                                    this.$emit('ok','add')
                                }else{
                                    this.$Message.error(message);
                                }
                            }).catch(e => {
                                this.$Message.error('创建任务失败');
                            }).finally(() => {
                                this.cancelLoading();
                            })
                        }
                    }else{
                        this.cancelLoading();
                    }
                }).catch(error => {
                    this.cancelLoading();
                })
            },
            initData(){
                this.formValidate = {...this._formValidate};
                this.selectGroups = [];
                this.optionalUsers = [];
            },
            resetField(){
                this.initData();
                this.$refs.formValidate.resetFields();
            },
            async showModal(data){
                this.type = data ? 'update' : 'add'
                this.modal.show = true;
                if(this.type == 'update'){
                    this.modal.title = '修改任务';
                    if(this.formValidate.taskType === 'EYDD'){
                        await this.getAccessGroupList();
                        let taskUserList = data.taskUserList.map(user => user.userId);
                        this.formValidate = {...data,...{taskUserList}};
                        let selectGroups = this.accessGroupList.filter(group => {
                            let groupUserList = group.userList.map(user => user.userId);
                            let result = (groupUserList.length + taskUserList.length) !== Array.from(new Set([...groupUserList,...taskUserList])).length;
                            return result
                        });
                        this.storeSaveUserList = taskUserList;
                        this.prevUserIds = '';
                        this.selectGroups = selectGroups.map(group => group.id);
                    }else{
                        this.getVmList()
                    }
                    // let users = selectGroups.reduce((users,group,index) => {
                    //     return [...users,...group.userList]
                    // },[])
                    // this.optionalUsers = users;
                    // setTimeout(() => {

                    // })
                }else{
                    this.modal.title = '创建任务';
                    if(this.formValidate.taskType === 'EYDD'){
                        this.getAccessGroupList();
                    }else{
                        this.getVmList()
                    }
                    this.initData();
                }
            },
            closeModal(){
                this.modal.show = false;
                this.$emit('close');
                this.resetField();
            },
            cancelLoading() {
                this.modal.loading = false;
                setTimeout(() => {
                    this.modal.loading = true;
                });
            },
            refreshVmList(){
                this.queryVm = {...this._queryVm};
                this.getVmList();
            },
            changeVmPage(page){
                this.queryVm.pageIndex = page
                this.getVmList();
            },
            changeVmSize(size){
                this.queryVm.pageSize = size
                this.getVmList();
            },
            // 虚拟机列表
            getVmList(){
                
                let params = {
                    pageIndex:this.queryVm.pageIndex,
                    pageSize:this.queryVm.pageSize,
                    order:"asc",
                    sortBy:"name",
                    name:this.queryVm.vmName,
                    ipAddress:this.queryVm.vmIP,
                    sysType:this.configerSystype,
                    projectId:this.projectId
                }
                getAllVm(params).then((response)=>{
                    this.vmList = [];
                    if(response.code==1){
                        
                        let vmData = response.data.items;
                        this.vmTotal = Number(response.data.total);
                        let disabled_ = false;
                        let checked_ = false;
                        vmData.forEach((item,i) => {
                            if(this.selectedVmDataTable.length!=0){
                                if(this.selectedVmDataTable.indexOf(item.id)!=-1){
                                    disabled_ = true
                                    checked_ = true
                                }else{
                                    disabled_ = false
                                    checked_ = false
                                }
                            }else{
                                disabled_ = false
                                checked_ = false
                            }
                            let IPS = [];
                            if(item.addresses&&item.addresses.length!=0){
                                for(let i=0;i<item.addresses.length;i++){
                                    if(item.addresses[i].ips&&item.addresses[i].ips.length!=0){
                                        for (let index = 0; index < item.addresses[i].ips.length; index++) {
                                            const element = item.addresses[i].ips[index];
                                            IPS.push(element.ipAddress);
                                        }
                                    }
                                }
                            }
                            this.vmList.push({
                                name:item.name,
                                id:item.id,
                                sysType:item.sysType,
                                IP:IPS,
                                _disabled: disabled_,
                                _checked:checked_,

                            })
                        })
                    }
                })
            },
            changeTaskType(type){
                if(type === 'EYDD'){
                    this.getAccessGroupList();
                }else{
                    // 加载配置列表
                    this.loadConfiguration();
                    this.getVmList();
                }
            },
            // 配置列表
            loadConfiguration(){
                let params = {
                    "operation":this.formValidate.taskType,
                    "createType":"all",
                    size: 2147483647
                };
                loadItemConfiguration(params).then((response)=>{
                    this.configList = [];
                    if(response.code==1||response.code==0){
                        let configList = response.data.list;
                        if(configList==""){
                            return;
                        }
                        this.configList = configList.map(item => {
                            return {
                                name:item.name,
                                id:String(item.id),
                            }
                        })
                    }else{
                        this.$Message.error(response.message)
                    }
                })
            },
            getConfigInfo(value){
                return new Promise((resolve,reject) => {
                    showConfiguration(value).then(res => {
                        let {code,data,message} = res;
                        if(code === 1){
                            resolve(data)
                        }else{
                            this.$Message.error(message);
                            reject();
                        }
                    }).catch(error => {
                        reject();
                    })
                })
            },
            async showConfiguration(value){
                this.configurationInformation = false
                this.selectedVmDataTable = [];
                this.formValidate.selectedVmData = [];
                let configInfo = await this.getConfigInfo();
                if(value){
                    axios({
                        url: '/tasktemplate/item/' + value,
                        method: 'get',
                    }).then( (response) => {
                        if(response.code != '1'){
                            this.$Message.info(response.message);
                            this.configerParams = false;
                        }else{
                            // _this.configerParams = true;
                            this.formValidate.category = response.data.category ?  response.data.category: ''
                            this.formValidate.path = response.data.data.path ? response.data.data.path:''
                            this.formValidate.type = response.data.data.type ? response.data.data.type:''
                            this.formValidate.content = response.data.data.content ? response.data.data.content: ''
                            this.formValidate.osType = response.data.data.osType ? response.data.data.osType :''
                            this.metadataConfigerInfor =  response.data.data;
                            this.configPanel.configName = response.data.name;
                            this.metadataConfigerInfor['configurationName'] = response.data.name;
                            this.configerSystype = response.data.data.osType;
                            this.getVmList();

                        }
                    });
                }else{
                    _this.configerParams = false;
                    _this.formValidate.category = ""
                    _this.formValidate.path = ""
                    _this.formValidate.type = ""
                    _this.formValidate.content = ""
                    _this.formValidate.osType = ""
                    _this.configerSystype = "";
                    _this.getVmList({pageIndex:_this.vmCurrentPage,pageSize:_this.vmItemPage,order:"asc",sortBy:"name",name:_this.formValidate.vmName,ipAddress:_this.formValidate.vmIP,sysType:_this.configerSystype})
                }
            },
            mouseOverConfiger(e,value){
                clearTimeout(this.optionHoverEvent)
                let _this = this;
                this.optionHoverEvent = setTimeout(() => {
                    if(this.hoverCdraBol){
                        return;
                    }
                    this.configurationInformation = true
                    this.cardPanelLeft = e.layerX +30+ 'px'
                    this.cardPanelTop = e.layerY +35+'px'
                    showConfiguration(value).then(function (response) {
                        if(response.code != '1'){
                            _this.$Message.info(response.message);
                        }else{
                            _this.configPanel.configName = response.data.name
                            _this.configPanel.configPath = response.data.data.path
                            _this.configPanel.configSystype = response.data.data.osType
                            _this.configPanel.configContent = response.data.data.content
                            _this.configPanel.configDescription = response.data.description
                            _this.configPanel.configCreateTime = response.data.createTime
                            _this.configPanel.configCreatorName = response.data.creatorName
                            
                        }
                    });
                }, 300);
            },
            mouseLeaveConfiger(ev,value){
                clearTimeout(this.optionOutEvent)
                this.optionOutEvent = setTimeout(() => {
                    if(!this.hoverCdraBol){
                        this.configurationInformation = false
                        this.cardPanelLeft = '0'
                        this.cardPanelTop = '0'
                    }
                }, 300);
            },
            jinru(e){
                this.hoverCdraBol = true
            },
            yichu(e){
                this.hoverCdraBol = false
                this.configurationInformation = false
                this.cardPanelLeft = '0'
                this.cardPanelTop = '0'
            },
            ddd(e){
                e.preventDefault()
                e.stopPropagation();
            },
            addSelectedData(){
                let that = this,bol = true;
                that.selectedDataConfiger.forEach((item,i) => {
                    console.log(item)
                    if(that.selectedVmDataTable.indexOf(item.id)!=-1){
                        
                    }else{
                        bol = false
                        that.addVmAfterTable(item)
                        that.selectedVmDataTable.push(item.id)
                        that.formValidate.selectedVmData.push({
                            "name":item.name,
                            "id":item.id
                        })
                    }
                })
                if(bol){
                    that.$Message.info("请选择要添加的内容")
                }
            },
            addVmAfterTable(param){
                this.vmList.forEach((item,i) => {
                    if(item.id==param.id){
                        item._checked = true;
                        item._disabled = true;
                    }
                })
            },
            getSelectedData(selection){
                // console.log(selection)
                this.selectedDataConfiger = [];
                this.selectedDataConfiger = selection;
            },
            getMsgFormSon(data){
                this.propertiesData = data;
            },
        }
    }
</script>
<style scoped>
</style>